import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'drf2.settings'
import django
django.setup()
from aaa import models

first_dict = {}
second_dict = {}

def rights():
    x = models.Role.objects.filter(permissions__isnull=False).values('id', 'roleName', 'roleDesc', 'permissions__id',
                                                                     'permissions__authName',
                                                                     'permissions__url',
                                                                     'permissions__level',
                                                                     'permissions__pid').distinct()
    for item in x:
        role_id = item['id']
        print('role_id',role_id)
        level = item['permissions__level']
        id = item['permissions__id']
        pid = item['permissions__pid']
        node = {'id': item['permissions__id'], 'authName': item['permissions__authName'], 'url': item['permissions__url'],
                'level':level,
                'pid':pid}
        if level == '0':
            if role_id in first_dict:
                first_dict[role_id]['children'].append(node)
            else:
                first_dict[role_id] = {'id':role_id,'roleName':item['roleName'],'roleDesc':item['roleDesc'],'children':[node]}
        #找出角色{1: {'id': 1, 'roleName': '运维', 'roleDesc': 'yunwei'}, 2: {'id': 2, 'roleName': '研发', 'roleDesc': 'yanfa'}}
        # first_dict[role_id] = {'id': role_id, 'roleName': item['roleName'], 'roleDesc': item['roleDesc']}
        #一级权限没有pid，只对二级三级权限操作
        if pid:
            # print('1      second_dict',second_dict)
            #拥有相同pid的二级三级权限归类到(role_id,pid)下，格式：
            '''{
                (1, 8): { #二级菜单
                    'children': [node1,node2]
                }, (1, 7): {
                    'children': [node}]
                }, (1, 4): { #三级菜单
                    'children': [node1,node2]
                }, (2, 7): {
                    'children': [node]
                }
            }'''
            if (role_id,pid) in second_dict:
                #if去重重复的二级菜单
                # print(level, node)
                print('11      second_dict', role_id,pid)
                # if node in second_dict[role_id,pid]['children']:
                #     continue
                # else:
                    #添加三级菜单
                if level == 2:
                    continue
                else:
                    second_dict[role_id,pid]['children'].append(node)

            else:

                second_dict[role_id,pid] = {'children':[node]}
        # else:
            # first_dict[role_id] = {'id':role_id,'roleName':item['roleName'],'roleDesc':item['roleDesc'],'children':[node]}
    print('------->first_dict',first_dict)
    return first_dict,second_dict


if __name__ == '__main__':
    rights()